﻿//---------------------Kendo grid---------------------------//
/*
selector:选择器
columns:列配置
url:Ajax地址
queryParams:查询参数
*/
function KendoGrid(selector, columns, url, queryParams, options) {
    //初始化以后的grid
    this.Grid = null;

    //容器
    this.Selector = selector;

    //列配置
    this.Columns = columns;

    //每行第一列是否需要CheckBox
    this.IsCheckbox = true,

    //选中事件
    this.onCheck = null;

    //选中第一条数据
    this.SelectFirst = null;

    //主键
    this.IdField = null;

    //ajax地址
    this.Url = url;

    //
    this.Method = 'get';

    //高度
    this.Height = null;

    //是否服务端分页
    this.Pagination = true;

    //数据源
    this.DataSource = null;

    //事件配置
    this.EventConfig = {};

    //参数
    this.QueryParams = queryParams;

    var defaulfOptions = {};
    options = $.extend(defaulfOptions, options || {});
    //---------------私有方法--------------------
    var privateMethod = {
        //查询参数方法
        queryParamFn: function (param) {
            var oThis = this;
            $.extend(param, oThis.QueryParams);
            return param;
        },

        //加载失败
        loadError: function (status, res) {
            try {
                var data = eval('(' + res.responseText + ')');
                if (data.message) {
                    $.msgError(data.message);
                } else {
                    $.msgError('数据加载失败！');
                }
            } catch (e) {
                $.msgError('数据加载失败！');
            }
        },

        //加载成功
        loadSuccess: function () {
            if (options.loadSuccessCallBack) {
                options.loadSuccessCallBack();
            }
        }
    };

    //确定好配置，初始化
    this.init = function () {

        var oThis = this;

        columns.splice(0, 0, {
            title: '',
            template: '<input type="checkbox" value="#=id#" />',
            width: 40,
            attributes: {
                "class": "table-cell",
                style: "text-align: center;"
            },
            hidden: !oThis.IsCheckbox
        });

        //设置表头样式
        $.each(columns, function () {
            $(this)[0]['headerAttributes'] = { style: "padding:0em .6em" }
        });

        var dataSource = {
            transport: {
                read: {
                    url: oThis.Url,
                    type: oThis.Method,
                    dataType: "json",
                    data: {}
                }
            },
            schema: {
                data: function (data) {
                    return data.rows;
                },
                total: function (data) {
                    return data.total;
                },
                model: {
                    id: 'id'
                }
            },
            pageSize: 10,
            serverPaging: oThis.Pagination,
            serverFiltering: false,
            serverSorting: false
        }

        var config = {
            groupable: false,
            sortable: false,
            scrollable: false,
            navigatable: false,
            selectable: "multiple, row",
            columnMenu: false,
            pageable: {
                refresh: false,
                pageSizes: false,
                buttonCount: 5,
                messages: {
                    display: "第 {0} 至 {1} 条，总共 {2} 条"
                }
            },
            columns: oThis.Columns
        };

        //bugfix 2017.2.14 柴自强
        //不应该在内部直接初始化事件配置
        // 应该在包容外部入参的情况下兼容的附加事件配置
        if (oThis.EventConfig) {
            oThis.EventConfig["onLoadSuccess"] = privateMethod.loadSuccess;
            oThis.EventConfig["onLoadError"] = privateMethod.loadError;
        } else {
            oThis.EventConfig = {
                onLoadSuccess: privateMethod.loadSuccess,
                onLoadError: privateMethod.loadError
            };
        }
        if (oThis.Height) {
            config['height'] = oThis.Height;
        }
        if (oThis.IdField) {
            dataSource.schema.model['id'] = oThis.IdField;
        }

        //自定义加载器
        dataSource.transport.read['data'] = function (param) {
            return privateMethod.queryParamFn.call(oThis, param);
        };

        //事件配置
        config['change'] = function (e) {
            oThis.Grid.tbody.find('[type=checkbox]').prop('checked', false);
            $(oThis.Selector + ' tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
            if (oThis.onCheck) {
                oThis.onCheck();
            }
        }
        config['dataBound'] = function () {
            $(oThis.Selector + " table").find('[type=checkbox]').on("change", function (e) {
                $(e.target).closest("tr").toggleClass("k-state-selected");
            });
            //选中第一条数据
            if (oThis.SelectFirst) {
                oThis.Grid.select("tr:eq(1)");
            }
        }

        if (oThis.EventConfig) {
            for (var eventName in oThis.EventConfig) {
                if (oThis.EventConfig.hasOwnProperty(eventName)) {
                    config[eventName] = oThis.EventConfig[eventName];
                }
            }
        }

        //加载失败
        dataSource['error'] = function (e) {
            var status = e.status;
            var res = e.xhr;
            //身份失效
            var headerJson = res.getResponseHeader("X-Responded-JSON");
            if (headerJson) {
                var headerJsonObj = eval('(' + headerJson + ')');
                if (headerJsonObj.status === 401) {
                    window.location.reload();
                    return false;
                }
            }
            if (oThis.EventConfig && oThis.EventConfig['onLoadError']) {
                oThis.EventConfig['onLoadError'](status, res);
            }
            return true;
        }

        config['dataSource'] = dataSource;

        oThis.DataSource = new kendo.data.DataSource(dataSource);

        oThis.Grid = $(oThis.Selector).kendoGrid(config).data("kendoGrid");

        oThis.DataSource.fetch(function () {
            var page = oThis.DataSource.totalPages();
            if (page < 2) {
                oThis.Grid.setOptions({
                    pageable: {
                        refresh: false,
                        numeric: false,
                        previousNext: false,
                        info: true,
                        messages: {
                            display: "第 {0} 至 {1} 条，总共 {2} 条"
                        }
                    }
                });
            }
            //数据加载成功事件
            if (oThis.EventConfig && oThis.EventConfig['onLoadSuccess']) {
                oThis.EventConfig['onLoadSuccess']();
            }
        });
    };

    //重新加载
    this.reload = function (queryParams) {
        var oThis = this;
        if (queryParams) {
            oThis.QueryParams = queryParams;
        }
        oThis.DataSource.fetch(function () {
            oThis.DataSource.transport.options.read.data(oThis.QueryParams);
            oThis.Grid.setDataSource(oThis.DataSource);
            var page = oThis.DataSource.totalPages();
            if (page < 2) {
                oThis.Grid.setOptions({
                    pageable: {
                        refresh: false,
                        numeric: false,
                        previousNext: false,
                        info: true,
                        messages: {
                            display: "第 {0} 至 {1} 条，总共 {2} 条"
                        }
                    }
                });
            } else {
                oThis.Grid.setOptions({
                    pageable: {
                        refresh: false,
                        pageSizes: false,
                        numeric: true,
                        previousNext: true,
                        buttonCount: 5,
                        messages: {
                            display: "第 {0} 至 {1} 条，总共 {2} 条"
                        }
                    }
                });
            }
        });

    }

    //销毁Grid
    this.destroy = function () {
        var oThis = this;
        oThis.Grid.destroy();
    }

    //获取选中项
    this.getSelections = function (isSingle) {
        var oThis = this;
        var data = [];
        var selectrow = oThis.Grid.select();
        if (isSingle) {
            if (!selectrow || selectrow.length === 0) {
                $.msgWarn('请选择要操作的数据！');
            }
            if (selectrow.length > 1) {
                $.msgWarn('只能选择一条数据操作！');
            }
        }
        $.each(selectrow, function () {
            data.push(oThis.Grid.dataItem($(this)));
        });
        return data;
    }


    //加载本地数据
    this.loadData = function (data) {
        var oThis = this;
        oThis.Grid.dataSource.data([]); //清空数据源
        oThis.Grid.dataSource.data(data.rows);
    }

    //选中
    this.selectRows = function (ids) {
        if (!ids || ids.length === 0) return;
        var oThis = this;
        var row = [];
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            var uid = oThis.Grid.dataSource.get(id).uid;
            if (uid) {
                row.push('tr[data-uid="' + uid + '"]');
            }
        }
        if (row.length > 0) {
            oThis.Grid.select(row.join(','));
        }
    }

    //获取选中项的Id
    this.getSelectId = function () {
        var oThis = this;
        var data = oThis.Grid.dataItem(oThis.Grid.select());
        return data.id;
    }

    //选中全部
    this.selectAll = function () {
        var oThis = this;
        oThis.Grid.select("tr");
    }

    //全部不选中
    this.unselectAll = function () {
        var oThis = this;
        oThis.Grid.tbody.find('tr').removeClass('k-state-selected');
        oThis.Grid.tbody.find('[type=checkbox]').prop('checked', false);
    }

    //显示列
    this.showColumns = function (columns) {
        var oThis = this;
        $.each(columns, function (index, item) {
            oThis.Grid.showColumn(item);
        });
    };
    //隐藏列
    this.hideColumns = function (columns) {
        var oThis = this;
        $.each(columns, function (index, item) {
            oThis.Grid.hideColumn(item);
        });
    };
};

